package com.zmn.plat.business.impl.product.businessline;

import java.util.*;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.StatusDTO;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.InitialUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.business.interfaces.product.businessline.ProductBusinessLineBService;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.common.dictionary.ProductDict;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.product.businessline.ProductBusinessLine;
import com.zmn.plat.model.entity.product.businessline.ProductBusinessLineQuery;
import com.zmn.plat.model.entity.product.productgroup.ProductGroup;
import com.zmn.plat.services.interfaces.product.businessline.ProductBusinessLineService;
import com.zmn.plat.services.interfaces.product.productgroup.ProductGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 描述: 产品业务线基础接口类
 *
 * @author tanbiao
 * @since 2020/10/27 14:52
 **/
@Service
@Slf4j
public class ProductBusinessLineBServiceImpl implements ProductBusinessLineBService {

    @Resource
    private ProductBusinessLineService productBusinessLineService;
    @Resource
    private ProductGroupService productGroupService;

    @Override
    public List<VtDTO> listVtByBizType(Integer bizType, Integer status) {

        if (NumberUtil.isNullOrZero(bizType)) {
            return Collections.emptyList();
        }

        ProductBusinessLineQuery query = new ProductBusinessLineQuery();
        query.setBizType(bizType);
        query.setStatus(status);
        List<ProductBusinessLine> items = productBusinessLineService.listByQuery(query);

        if (CollectionUtil.isNullOrEmpty(items)) {
            return Collections.emptyList();
        }

        List<VtDTO> dtos = items.stream().map(businessLine -> new VtDTO(businessLine.getRelateId(), businessLine.getName())).distinct().collect(Collectors.toList());

        return dtos;
    }

    @Override
    public ArrayList<List> outputProductExcel(ProductBusinessLineQuery query) {
        List<ProductBusinessLine> productGroupList = productBusinessLineService.listPageByQuery(query);
        ArrayList<List> arrayList = Lists.newArrayListWithExpectedSize(productGroupList.size() + 1);
        List<String> column = Arrays.asList(ProductConsts.ZMN_PRODUCT_BUSINESS_LINE_EXCEL_TITLE);
        arrayList.add(column);

        if (!productGroupList.isEmpty()) {
            productGroupList.forEach(productGroup -> {
                List<String> item = new ArrayList<>();
                item.add(productGroup.getSort().toString());
                item.add(productGroup.getRelateId().toString());
                item.add(Objects.isNull(productGroup.getBizType()) ? "-" : ProductDict.getBizTypeCNENName(productGroup.getBizType()));
                item.add(productGroup.getName());
                item.add(Objects.isNull(productGroup.getStatus()) ? "-" : GlobalDict.getStatus(productGroup.getStatus()));
                item.add(productGroup.getUpdater());
                item.add(Objects.isNull(productGroup.getUpdateTime()) ? "-" : DateUtil.toString(productGroup.getUpdateTime()));
                arrayList.add(item);
            });
        }
        return arrayList;
    }

    @Override
    public Integer addEdit(ProductBusinessLine productBusinessLine, String mcStaffRealName) {
        Date now = DateUtil.getNow();
        int relateId = productBusinessLine.getRelateId();

        try {
            Integer result = -1;
            if (relateId == 0) {
                productBusinessLine.setCreater(mcStaffRealName);
                productBusinessLine.setCreateTime(now);
                productBusinessLine.setUpdater(mcStaffRealName);
                productBusinessLine.setUpdateTime(now);
                // 排序值，默认100
                productBusinessLine.setSort(100);
                result = productBusinessLineService.insert(productBusinessLine);
            } else {
                productBusinessLine.setUpdater(mcStaffRealName);
                productBusinessLine.setUpdateTime(now);
                result = productBusinessLineService.updateByKey(productBusinessLine);
            }

            return result;
        } catch (org.springframework.dao.DuplicateKeyException ex) {
            log.error("同一业务类型名称不能重复！", productBusinessLine.getName());
            throw new PlatException("同一业务类型名称不能重复！");
        } catch (Exception e) {
            log.error("新增/修改失败, Exception{}, msg{}", e, e.getMessage());
            throw new PlatException("操作失败！");
        }
    }

    @Override
    public Integer updateStatus(String ids, int status, String mcStaffRealName) {
        if (StringUtil.isBlank(ids)) {
           throw new PlatException("请选择要更改状态的产品组！");
        }

        List<Integer> relateIds = StringUtil.convertStrsToList(ids);

        if (Objects.equals(GlobalConsts.NO, status)) {
            // 校验业务线是否有产品分组关联
            List<Integer> groupIdOfUsed = productGroupService.listProductGroupIdByBusinessLine(relateIds);
            if (CollectionUtil.isNotNullOrEmpty(groupIdOfUsed)) {
                throw new PlatException("已有产品组关联了业务线，暂不能禁用！");
            }
        }

        StatusDTO dto = new StatusDTO();
        dto.setIds(relateIds);
        dto.setStatus(status);
        dto.setUpdater(mcStaffRealName);
        dto.setUpdateTime(new Date());
        return productBusinessLineService.updateStatusBatch(dto);
    }
}
